package com.daxue.nacosprovider;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@Service
@Slf4j
public class KafkaProducer {

    final
    KafkaTemplate<String, String> kafkaTemplate;

    public static final String TOPIC_TEST = "test";

    public KafkaProducer(final KafkaTemplate<String, String> kafkaTemplate) {this.kafkaTemplate = kafkaTemplate;}

    public void send(Object obj) {

        String obj2String = JSONObject.toJSONString(obj);
        log.info("准备发送的消息为：{}", obj2String);

        String key = "a";

        for (int k = 0;k<5;k++) {
            for (int i =0; i< 10; i++) {
                // 发送消息
                ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(TOPIC_TEST, key + k, obj2String + i);
                future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
                    public void onFailure(final Throwable throwable) {
                        log.info("{} 生产者发送消息失败：{}", TOPIC_TEST, throwable.getMessage());
                    }

                    public void onSuccess(final SendResult<String, String> stringObjectSendResult) {
                        log.info("{} 生产者发送消息成功: {}", TOPIC_TEST,
                            JSONObject.toJSONString(stringObjectSendResult)
                        );
                    }
                });

            }

        }
        


    }

}
